package org.example.rzfx.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.rzfx.dto.LogExportDTO;
import org.example.rzfx.entity.Log;
import org.example.rzfx.mapper.LogMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 日志导出服务
 */
@Service
@Slf4j
public class LogExportService {
    
    @Resource
    private LogMapper logMapper;
    
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 导出日志为CSV格式
     */
    public byte[] exportToCsv(LogExportDTO exportDTO) {
        try {
            // 查询日志数据
            List<Log> logs = queryLogsForExport(exportDTO);
            
            // 生成CSV内容
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            
            // 写入BOM头，防止Excel乱码
            outputStream.write(0xEF);
            outputStream.write(0xBB);
            outputStream.write(0xBF);
            
            // 写入CSV表头
            writer.write("日志ID,采集源ID,时间戳,日志级别,系统类型,日志内容,创建时间\n");
            
            // 写入数据行
            for (Log log : logs) {
                writer.write(String.format("%d,%d,%s,%s,%s,\"%s\",%s\n",
                    log.getId(),
                    log.getSourceId(),
                    log.getTimestamp().format(FORMATTER),
                    log.getLogLevel(),
                    log.getSystemType(),
                    escapeCsv(log.getContent()),
                    log.getCreateTime().format(FORMATTER)
                ));
            }
            
            writer.flush();
            writer.close();
            
            return outputStream.toByteArray();
            
        } catch (Exception e) {
            log.error("导出日志失败", e);
            throw new RuntimeException("导出日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询需要导出的日志
     */
    private List<Log> queryLogsForExport(LogExportDTO exportDTO) {
        LambdaQueryWrapper<Log> wrapper = new LambdaQueryWrapper<>();
        
        if (exportDTO.getStartTime() != null) {
            wrapper.ge(Log::getTimestamp, exportDTO.getStartTime());
        }
        if (exportDTO.getEndTime() != null) {
            wrapper.le(Log::getTimestamp, exportDTO.getEndTime());
        }
        if (StrUtil.isNotBlank(exportDTO.getLogLevel())) {
            wrapper.eq(Log::getLogLevel, exportDTO.getLogLevel());
        }
        if (StrUtil.isNotBlank(exportDTO.getSystemType())) {
            wrapper.eq(Log::getSystemType, exportDTO.getSystemType());
        }
        if (StrUtil.isNotBlank(exportDTO.getKeyword())) {
            wrapper.like(Log::getContent, exportDTO.getKeyword());
        }
        
        wrapper.orderByDesc(Log::getTimestamp);
        
        // 限制导出数量，防止数据量过大
        wrapper.last("LIMIT 10000");
        
        return logMapper.selectList(wrapper);
    }
    
    /**
     * 转义CSV特殊字符
     */
    private String escapeCsv(String content) {
        if (content == null) {
            return "";
        }
        // 替换双引号为两个双引号
        return content.replace("\"", "\"\"")
                     .replace("\n", " ")
                     .replace("\r", "");
    }
}

